using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCWeb.Models;
using System.IO;
using System.Drawing;
using MVCWeb.Helpers;
using System.Drawing.Imaging;

namespace MVCWeb.Controllers
{
    public class VendorController : BaseController
    {
        //
        // GET: /Vendor/
        [Authorize(Roles="Administrators")]
        public ActionResult Index()
        {
            return View(this.dc.Vendors.OrderBy(v => v.VendorName).ToList<Vendor>());
        }

        //
        // GET: /Vendor/Details/5
        [Authorize(Roles = "Administrators")]
        public ActionResult Details(int id)
        {
            return View(this.dc.Vendors.Single(v => v.VendorId == id));
        }

        //
        // GET: /Vendor/Create
        [Authorize(Roles = "Administrators")]
        public ActionResult Create()
        {
            Vendor vendor = new Vendor();
            return View(vendor);
        } 

        //
        // POST: /Vendor/Create

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Create(Vendor vendorToCreate, FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                // TODO: Add insert logic here
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (hpf.ContentLength == 0)
                        continue;

                    string savePath = @"Uploads\Images\Vendors\";

                    string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                    if (!Directory.Exists(physicPath))
                    {
                        Directory.CreateDirectory(physicPath);
                    }

                    string sFilename = Path.GetFileName(hpf.FileName);
                    string savedFileName = Path.Combine(physicPath, sFilename);

                    string extension = Path.GetExtension(hpf.FileName).ToLower();

                    int file_append = 0;
                    while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                    {
                        file_append++;
                        sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName) + file_append.ToString() + extension;
                    }

                    // need to caculate correct width and height
                    int widthMax = 160;
                    int heightMax = 160;

                    savedFileName = Path.Combine(physicPath, sFilename);
                    hpf.SaveAs(savedFileName);

                    Image fullPicture;
                    try
                    {
                        // New image size.
                        fullPicture = new Bitmap(savedFileName);
                        Image original = ImageHelper.ResizeImage(fullPicture, widthMax, heightMax, ImageResizeOption.MaintainAspectWidth);
                        fullPicture.Dispose();

                        // Delete original image.
                        if (System.IO.File.Exists(savedFileName))
                        {
                            System.IO.File.Delete(savedFileName);
                        }

                        string ext = hpf.FileName.Substring(hpf.FileName.LastIndexOf('.'));
                        switch (ext.ToLower())
                        {
                            case ".jpg":
                                original.Save(savedFileName, ImageFormat.Jpeg);
                                break;
                            case ".png":
                                original.Save(savedFileName, ImageFormat.Png);
                                break;
                            case ".gif":
                                original.Save(savedFileName, ImageFormat.Gif);
                                break;
                            case ".bmp":
                                original.Save(savedFileName, ImageFormat.Bmp);
                                break;
                        }
                        original.Dispose();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error in create thumbnail: " + ex.Message);
                    }

                    vendorToCreate.LogoUrl = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                }

                //UpdateModel<Vendor>(vendorToCreate);
                this.dc.Vendors.InsertOnSubmit(vendorToCreate);
                this.dc.SubmitChanges();
                if (collection["IsRedirectToView"].Equals("true"))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    return Redirect(Request.RawUrl);
                }
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Vendor/Edit/5
        [Authorize(Roles="Administrators")]
        public ActionResult Edit(int id)
        {
            return View(this.dc.Vendors.Single(v => v.VendorId == id));
        }

        //
        // POST: /Vendor/Edit/5

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles="Administrators")]
        public ActionResult Edit(int id, Vendor vendorToEdit, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                

                vendorToEdit = this.dc.Vendors.Single(v => v.VendorId == id);
                string newLogoUrl = vendorToEdit.LogoUrl;

                foreach (string file in Request.Files)
                {
                    FileInfo oldFile = new FileInfo(Server.MapPath("~/" + vendorToEdit.LogoUrl));
                    if (oldFile.Exists)
                    {
                        oldFile.Delete();
                    }

                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (hpf.ContentLength == 0)
                        continue;

                    string savePath = @"Uploads\Images\Vendors\";

                    string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                    if (!Directory.Exists(physicPath))
                    {
                        Directory.CreateDirectory(physicPath);
                    }

                    string sFilename = Path.GetFileName(hpf.FileName);
                    string savedFileName = Path.Combine(physicPath, sFilename);

                    string extension = Path.GetExtension(hpf.FileName).ToLower();

                    int file_append = 0;
                    while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                    {
                        file_append++;
                        sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName) + file_append.ToString() + extension;

                    }

                    savedFileName = Path.Combine(physicPath, sFilename);

                    hpf.SaveAs(savedFileName);


                    // need to caculate correct width and height
                    int widthMax = 200;
                    int heightMax = 200;

                    savedFileName = Path.Combine(physicPath, sFilename);
                    hpf.SaveAs(savedFileName);

                    Image fullPicture;
                    try
                    {
                        // New image size.
                        fullPicture = new Bitmap(savedFileName);
                        Image original = ImageHelper.ResizeImage(fullPicture, widthMax, heightMax, ImageResizeOption.MaintainAspectWidth);
                        fullPicture.Dispose();

                        // Delete original image.
                        if (System.IO.File.Exists(savedFileName))
                        {
                            System.IO.File.Delete(savedFileName);
                        }

                        string ext = hpf.FileName.Substring(hpf.FileName.LastIndexOf('.'));
                        switch (ext.ToLower())
                        {
                            case ".jpg":
                                original.Save(savedFileName, ImageFormat.Jpeg);
                                break;
                            case ".png":
                                original.Save(savedFileName, ImageFormat.Png);
                                break;
                            case ".gif":
                                original.Save(savedFileName, ImageFormat.Gif);
                                break;
                            case ".bmp":
                                original.Save(savedFileName, ImageFormat.Bmp);
                                break;
                        }
                        original.Dispose();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error in create thumbnail: " + ex.Message);
                    }

                    newLogoUrl = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                }

                UpdateModel<Vendor>(vendorToEdit);
                vendorToEdit.LogoUrl = newLogoUrl;
                this.dc.SubmitChanges();
                if (collection["IsRedirectToView"].Equals("true"))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    return Redirect(Request.RawUrl);
                }
            }
            catch
            {
                return View();
            }
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add update logic here.
                Vendor vendor = this.dc.Vendors.Single(v => v.VendorId == id);
                this.dc.Vendors.DeleteOnSubmit(vendor);
                this.dc.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
